#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define PORT 8888
#define N 64

int main()
{
	int server_fd,client_fd;
	int ret;
	char buf[N] = "";
	struct sockaddr_in server_addr,client_addr;
	socklen_t addrlen = sizeof(server_addr);
	server_fd = socket(AF_INET,SOCK_STREAM,0);

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(PORT);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	ret = bind(server_fd, (struct sockaddr *)&server_addr, addrlen);
	if(ret == -1)
	{
		perror("Fail to bind");
		return -1;
	}
	printf("Success to bind\n");

	ret = listen(server_fd, 5);
	if(ret == -1)
	{
		perror("Fail to listen");
		return -1;
	}
	printf("Success to listen\n");

	client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addrlen);
	if(client_fd == -1)
	{
		perror("Fail to accept");
		return -1;
	}
	printf("Success to accept\n");
	printf("Client IP: %s\n",inet_ntoa(client_addr.sin_addr));

	while(1)
	{
		ssize_t rect;
		rect = recv(client_fd, buf, N, 0);
		if(rect > 0)
		{
			printf("Recive: %s\n",buf);
			memset(buf,0,N);
		}
		else if(rect == 0)
		{
			perror("Perr exit");
			close(client_fd);
			close(server_fd);
			return -1;
		}
		else
		{
			perror("Recv Error");
            close(client_fd);
            close(server_fd);
			return -1;
		}
	}

	return 0;
}
